<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    //用户发表的文章数
    public function posts()
    {
        return $this->hasMany(\App\Post::class, 'user_id', 'id');
    }

    //关注我的fan模型
    public function fans()
    {
        return $this->hasMany(\App\Fan::class, 'star_id', 'id');
    }

    //我关注的用户
    public function stars()
    {
        return $this->hasMany(\App\Fan::class, 'fan_id', 'id');
    }

    //关注某人
    public function doFan($userId)
    {
        $fan = new \App\Fan();
        $fan->star_id = $userId;

        return $this->stars()->save($fan);
    }

    //取消关注某人
    public function doUnfan($userId)
    {
        $fan = new \App\Fan();
        $fan->star_id = $userId;

        return $this->stars()->delete($fan);
    }

    //当前用户是否被$uid关注
    public function hasFan($uid)
    {
//        return in_array($uid, $this->fans());
        return $this->fans()->where('fan_id', $uid)->count();
    }

    //当前用户是否关注 $uid
    public function hasStar($uid)
    {
//        return in_array($uid, $this->stars());
        return $this->stars()->where('star_id', $uid)->count();
    }

    //用户拥有的通知
    public function notices()
    {
        return $this->belongsToMany(\App\Notice::class, 'user_notice', 'user_id', 'notice_id')->withPivot(['user_id', 'notice_id']);
    }

    //添加消息
    public function addNotice($notice)
    {
        return $this->notices()->save($notice);
    }
}
